package com.hngy.educationaladministration.controller;

import com.hngy.educationaladministration.auth.Authority;
import com.hngy.educationaladministration.auth.Role;
import com.hngy.educationaladministration.config.ParamContext;
import com.hngy.educationaladministration.controller.convert.StudentConvert;
import com.hngy.educationaladministration.entity.*;
import com.hngy.educationaladministration.entity.co.CourseTableCo;
import com.hngy.educationaladministration.mapper.SubjectselectedMapper;
import com.hngy.educationaladministration.service.*;
import com.hngy.educationaladministration.service.serviceImpl.IndexServiceImpl;
import com.hngy.educationaladministration.service.serviceImpl.LoginServiceImpl;
import com.hngy.educationaladministration.utils.MD5Util;
import com.hngy.educationaladministration.utils.TokenUtil;
import com.hngy.educationaladministration.utils.WeatherUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Authority(roles = {Role.STUDENT})
@Controller
@RequestMapping("/student")
@Slf4j
public class StudentController {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LoginServiceImpl loginService;

    @Autowired
    IndexServiceImpl indexService;

    @Autowired
    AdminService adminService;

    @Autowired
    private UpLoadFileService upLoadFileService;

    @Autowired
    TopicsService topicsService;

    @Autowired
    private FileTableService fileTableService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ProjectService projectService;

    @Autowired
    private CourseTableService courseTableService;

    @Autowired
    private WeatherService weatherService;

    //Session过期时间
    private final Integer SAVE_TIME = 60 * 60 * 24;


    @GetMapping("/login")
    public String login() {
        return "student/login";
    }


    @PostMapping(value = "/login")
    @ResponseBody
    public String login(String name, String pwd, Model model, HttpServletResponse response, HttpServletRequest request) {
        //天气生成
        WeatherUtil.setWeatherForController(request);
        name = name.trim();
        Student student = studentService.selectStudentInfo(name, pwd);
        if (!Objects.isNull(student)) {
            request.getSession().setAttribute("student", student);
            request.getSession().setMaxInactiveInterval(SAVE_TIME);
            User user = new User();
            //-1表示为超管
            user.setId(1L);
            user.setRole("student");
            user.setUserName(name);
            //生成Token 存到 Cookie
            Cookie cookie = new Cookie("token", TokenUtil.createToken(
                    user
            ));
            //该Cookie无法被js读取
            cookie.setHttpOnly(true);
            cookie.setPath("/");
            response.addCookie(cookie);
            model.addAttribute("student", student);
            return "200";
        } else {
            return "0";
        }
    }


    @RequestMapping("/index")
    public String index(Model model, HttpSession httpSession) {
        Student student = (Student) request.getSession().getAttribute("student");
        Subject project = indexService.indexinfo(student.getId());
        String str = null;
        Long flag = null;
        if (project == null) {
            model.addAttribute("projectName", "未选课程");
            model.addAttribute("flag", "未选课");
            model.addAttribute("teacher", "无");
            httpSession.removeAttribute("");
        } else {
            httpSession.setAttribute("XZproject", project.getProjectname());
            model.addAttribute("XZproject", project.getProjectname());
            model.addAttribute("projectName", project.getProjectname());
            flag = indexService.projectselectedstuflag(student.getId());
            if (flag == 0L) {
                str = "未选课";
            } else if (flag == 101L) {
                str = "选课待审核";
            } else if (flag == 2L) {
                str = "选课未通过";
            } else if (flag == 3L) {
                str = "选课通过";
            }
            model.addAttribute("flag", str);
            model.addAttribute("teacher", project.getTeachernames());
            request.getSession().setAttribute("filePath", project.getFilepath());
        }
        //用来判断当前页是否为首页
        model.addAttribute("path", "1");
        //判断是否修改了个人信息
//        request.getSession().setAttribute("modifyFlag",0);

        return "student/index";
    }


    /**
     * 查看个人信息
     */
    @RequestMapping("/studentinfo")
    public String studentinfo(Model model) {
        Student student = (Student) request.getSession().getAttribute("student");
        MyClass idclass = indexService.studentinfo(student.getIdClass());
        model.addAttribute("tclass", idclass);
        return "student/studentinfo";
    }

    /**
     * 将查看的个人信息放到信息修改页面
     */
    @RequestMapping("/modifyinfo")
    public String modifyinfo(Model model) {
        Student student = (Student) request.getSession().getAttribute("student");
        MyClass idclass = indexService.studentinfo(student.getIdClass());
        model.addAttribute("tclass", idclass);

        return "student/modifyinfo";
    }


    /**
     * 修改个人信息
     * 根据班级(className)修改
     */
    @RequestMapping(value = "/modifyinfodao", method = RequestMethod.PUT)
    @ResponseBody
    public String modifyinfodao(Student student, String className, Model model) {
        Student Tstudent = (Student) request.getSession().getAttribute("student");
        MyClass Tclass = indexService.selectByclassName(className);
        int count = -1;
        student.setIdClass(Tclass.getId());
        System.out.println("******" + Tstudent.toString());
        System.out.println("******" + student.toString());

        if (student.getStunum().equals(Tstudent.getStunum())) {
            student.setStunum(null);
        }
        if (student.getIdClass().equals(Tstudent.getIdClass())) {
            student.setIdClass(null);
        }
        if (student.getName().equals(Tstudent.getName())) {
            student.setName(null);
        }
        if (student.getGender().equals(Tstudent.getGender())) {
            student.setGender(null);
        }
        if (student.getGender() == null && student.getName() == null && student.getIdClass() == null && student.getStunum() == null) {

        } else {
            student.setId(Tstudent.getId());
            count = indexService.updateBymodifyinfo(student);
            student = indexService.selectByid(Tstudent.getId());
            model.addAttribute("student", student);
        }
        if (count > 0) {
            request.getSession().setAttribute("student", student);
            request.getSession().setAttribute("modifyFlag", 1);
            return "200";
        } else {
            request.getSession().setAttribute("modifyFlag", 0);
            return "201";
        }
    }


    /**
     * 跳转页面(修改密码)
     */
    @RequestMapping("/changepsw")
    public String changepsw() {
        return "student/changepsw";
    }


    /**
     * 200修改成功
     * 201对不起密码错误
     * 202对不起输入框为空
     * 203新密码不一致
     * 204修改失败
     */
    @RequestMapping(value = "/changepassword", method = RequestMethod.PUT)
    @ResponseBody
    public String changepswdao(String oldpassword, String newpassword, String newpassword1) {
        if (!verifypassword(newpassword)) {
            return "206";
        }
        if (!verifypassword(newpassword1)) {
            return "206";
        }
        Student student = (Student) request.getSession().getAttribute("student");
        Student studentdao = loginService.selectByName(student.getUsername());
        int result;
        if (newpassword.equals(newpassword1) && !newpassword.equals("") && !newpassword1.equals("")) {
            if (studentdao.getPwd().equals(MD5Util.encrypt32(student.getUsername() + oldpassword))) {

                if (oldpassword.equals(newpassword)) {
                    return "205";
                } else {
                    result = indexService.updatepassword(MD5Util.encrypt32(student.getUsername() + newpassword), student.getId());
                    if (result > 0) {
                        return "200";
                    } else {
                        return "204";
                    }
                }
            } else {
                return "201";
            }
        } else if (newpassword.equals("") && newpassword1.equals("")) {
            return "202";
        }
        return "203";
    }


    //密码验证
    public boolean verifypassword(String password) {
        if (password.length() < 6 || password.length() > 16) {
            return false;
        }
        for (int i = 0; i < password.length(); i++) {
            if (!(password.charAt(i) >= 'A' && password.charAt(i) <= 'Z')) {
                if (!(password.charAt(i) >= 'a' && password.charAt(i) <= 'z')) {
                    if (!(password.charAt(i) >= '0' && password.charAt(i) <= '9')) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //退出
    //清除Session数据
    @RequestMapping("/exit")
    public String exit(HttpServletResponse response, HttpSession httpSession) {
//        httpSession.setAttribute("XZproject", null);
//       清除Session
        Enumeration em = request.getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        //将Cookie 中的token 置空
        Cookie cookie = new Cookie("token", null);
        cookie.setPath("/");
        response.addCookie(cookie);

        return "student/login";
    }


    /**
     * 查看班级选报信息
     */
    @RequestMapping("/classinfo")
    public String classinfo(Model model, HttpSession httpSession) {

        Student student = (Student) request.getSession().getAttribute("student");
        removeSession();
        List<Static_student> list = adminService.select_student(null, null, student.getIdClass(), null, null);

        System.out.println(list);
        model.addAttribute("list", list);
        return "student/classinfo";
    }


    /**
     * 查看课程
     */
    @RequestMapping("/topics")
    public String Topics(Model model, HttpSession httpSession) {
        Student student = (Student) request.getSession().getAttribute("student");
        removeSession();
        List<topicsinfo> topicsinfolist = topicsService.topics(student.getIdClass());
        System.out.println(topicsinfolist);
        model.addAttribute("topicsinfolist", topicsinfolist);
        return "student/topicsinfo";
    }


    /**
     * 课程具体信息
     */
    @RequestMapping("/topicsto")
    public String Topicsto(Long project_id, int selectFlag, String projectName, Model model, HttpSession httpSession) {
        List<topicsto> topicstos = topicsService.topicsinfo(project_id);
        Student student = (Student) request.getSession().getAttribute("student");
        Long flag = topicsService.state(student);
        Long flagto = topicsService.flag(project_id);
        if (flagto != 0) {
            flag = 3L;
        }
        model.addAttribute("selectFlag", selectFlag);
        model.addAttribute("flag", flag);
        model.addAttribute("topicstos", topicstos);
        model.addAttribute("projectName", projectName);
        model.addAttribute("project_id", project_id);
        /**
         * save teacher and project id
         */
        request.getSession().setAttribute("project_id", project_id);
        request.getSession().setAttribute("teacher_id", projectService.getProjectInfoById(project_id).getIdTeacher());

        model.addAttribute("XZproject", httpSession.getAttribute("XZproject"));

        Subjectselected subjectselected = subjectselectedMapper.selectBySidPid(student.getId(), project_id);
        if (subjectselected == null) {
            httpSession.setAttribute("myflag", 0);
            model.addAttribute("myflag", 0);
        } else if (subjectselected.getStuselectFlag().equals(101L)) {
            httpSession.setAttribute("myflag", 1);
            model.addAttribute("myflag", 1);
        } else if (subjectselected.getStuselectFlag().equals(2L)) {
            httpSession.setAttribute("myflag", 2);
            model.addAttribute("myflag", 2);
        }
//        LOGGER.info(httpSession.getAttribute("myflag").toString());
        return "student/topicsinfoto";
    }


    /**
     * 选报课程
     */
    @Autowired
    SubjectselectedMapper subjectselectedMapper;

    @RequestMapping("/enroll")
    @ResponseBody
    public String enroll(Long project_id, HttpSession httpSession) {
        String projectName = topicsService.selectprojectname(project_id);
        Student student = (Student) request.getSession().getAttribute("student");
        Subjectselected subjectselected = subjectselectedMapper.selectBySidPid(student.getId(), project_id);
        if (subjectselected == null) {
            studentService.updateselectnumAdd(projectName);
            topicsService.insertproject(projectName, student.getId());
            httpSession.setAttribute("XZproject", projectName);
            return "200";
        } else if (subjectselected.getStuselectFlag().equals(101L)) {
            return "101";
        } else {
            return "201";
        }
    }

    /**
     * 取消选报
     */
    @RequestMapping("/cancel")
    @ResponseBody()
    public String cancel(Long project_id, Model model, HttpSession httpSession) {
        String projectName = topicsService.selectprojectname(project_id);
        Student student = (Student) request.getSession().getAttribute("student");
        List<Subjectselected> subjectselected = subjectselectedMapper.selectBystudentid(student.getId());

        if (subjectselected != null && subjectselected.size() != 0 && subjectselected.get(0).getStuselectFlag() != 3
                && project_id.equals(subjectselected.get(0).getIdProject())) {

//            topicsService.deleteprojectselectedid(student.getId());
            subjectselectedMapper.deleteBySidPid(student.getId(), project_id);
            httpSession.removeAttribute("XZproject");
            model.addAttribute("XZproject", null);
            httpSession.setAttribute("XZproject", null);
            studentService.updateselectnumReduce(projectName);
            return "200";

        } else {
            return "203";
        }
    }

    /**
     * 取消选报
     */
    @RequestMapping("/cancelproject")
    @ResponseBody()
    public String cancelProject(Long project_id, Model model, HttpSession httpSession) {
        String projectName = topicsService.selectprojectname(project_id);
        Student student = (Student) request.getSession().getAttribute("student");
        List<Subjectselected> subjectselected = subjectselectedMapper.selectBystudentid(student.getId());
        subjectselectedMapper.deleteBySidPid(student.getId(), project_id);
        httpSession.removeAttribute("XZproject");
        model.addAttribute("XZproject", null);
        httpSession.setAttribute("XZproject", null);
        studentService.updateselectnumReduce(projectName);
        return "200";
    }

    /**
     * 清除session中存的项目名
     */
    public void removeSession() {
        Student student = (Student) request.getSession().getAttribute("student");
        Subject project = indexService.indexinfo(student.getId());
        if (project == null) {
            request.getSession().removeAttribute("XZproject");
        }
    }


    @GetMapping("/courseinfo")
    public String getCourse(Model model) {
        //获取student信息，
        Student student = (Student) request.getSession().getAttribute("student");
        //System.out.println(student);//Student(id=7646, username=计软2017-1-01, stunum=1, idClass=29, name=学生1, gender=女, pwd=11111111)
        List<Course> course = studentService.getCourse(student);
        model.addAttribute("course", course);
        return "/student/courseinfo";
    }

    // 上传作业
    @PostMapping("/upProjectFromStudent")
    @ResponseBody
    public Msg upProjectFromStudent(@RequestParam("file") MultipartFile file, Long project_id, HttpServletRequest request) throws IOException {
        if (file == null) {
            return Msg.fail().add("msg", "文件上传失败");
        }
        //获取student信息，
        Student student = (Student) request.getSession().getAttribute("student");
        //获取上传文件的原名
        String uploadFileName = file.getOriginalFilename();
        uploadFileName = uploadFileName.substring(uploadFileName.lastIndexOf(File.separator) + 1);
        File path = new File(ResourceUtils.getURL("target").getPath());
        String savePath =
                path.getAbsolutePath() + File.separator + "classes+" + File.separator + "static"
                        + File.separator + "model" + File.separator + student.getId();
        String saveFileName = savePath + File.separator + uploadFileName;
        File dirs = new File(savePath);
        //判断路径是否存在，如果不存在就创建一个
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        // 开始接受文件
        file.transferTo(new File(dirs, uploadFileName));

        upLoadFileService.UpLoadBySidPid(student.getId(), project_id, saveFileName);
        return Msg.success();
    }


    /**
     * 上传的是单个文件
     */
    @ResponseBody
    @RequestMapping("uploadFile")
    public void uploadFile(@RequestParam("file") MultipartFile inputFile, HttpServletRequest request) {
        if (inputFile == null) {
            System.out.println("没有想要上传的文件");
        } else {
            try {
                String originalFileName = inputFile.getOriginalFilename(); // 获取原始文件名
                String savePath = "F:\\";
                File savePathDir = new File(savePath);
                System.out.println("文件原始名称:" + originalFileName);
                System.out.println("原始文件大小: " + inputFile.getSize());
                if (!savePathDir.exists()) {
                    savePathDir.mkdirs();
                }
                inputFile.transferTo(new File(savePath, originalFileName));
                log.info(originalFileName + "上传成功");
            } catch (NullPointerException e) {

            } catch (Exception e) {

            }

        }
    }

    /**
     * 上传的是多个文件
     */
    @ResponseBody
    @RequestMapping("uploadFiles")
    public void uploadFiles(@RequestParam("files") MultipartFile[] inputFiles, HttpServletRequest request) {
        if (inputFiles.length < 1) {
            System.out.println("没有想要上传的文件");
        } else {
            try {
                for (int i = 0; i < inputFiles.length; i++) {
                    String originalFileName = inputFiles[i].getOriginalFilename(); // 获取原始文件名
                    long fileSize = inputFiles[i].getSize();        // 文件大小
                    String savePath = "E:\\";      // 文件保存地址
                    File savePathDir = new File(savePath);

                    if (!savePathDir.exists()) {
                        savePathDir.mkdirs();
                    }
                    inputFiles[i].transferTo(new File(savePath, originalFileName));
                    log.info(originalFileName + "上传成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * get student upload files
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/getAllFiles")
    public String getAllFiles(HttpServletRequest request, Model model) {
        //获取student信息
        Student student = (Student) request.getSession().getAttribute("student");
        //id作为文件夹名
        Long id = student.getId();
        List<FileTable> allFileBySid = fileTableService.getAllFileBySid(id.intValue());
        for (FileTable fileTable : allFileBySid) {
            getStudentName(fileTable);
            String url = fileTable.getUrl();
            int length = url.length();
            String substring = url.substring(url.lastIndexOf('.') + 1, length);
            if (substring.equals("doc") || substring.equals("docx")) {
                fileTable.setLookOnline(url + ParamContext.DOC);
            } else if (substring.equals("jpg") || substring.equals("jpeg")) {
                fileTable.setLookOnline(url + ParamContext.JPEG);
            } else if (substring.equals("gif")) {
                fileTable.setLookOnline(url + ParamContext.GIF);
            }
        }
        model.addAttribute("allFiles", allFileBySid);
        return "/student/myUpload";
    }

    @Autowired
    private ScoreService scoreService;

    public void getStudentName(FileTable fileTable) {
        fileTable.setStudentName(studentService.getStudentInfoBySid(fileTable.getSid().longValue()).getName());
        fileTable.setTeacherName(teacherService.getTeacherInfoByTid(fileTable.getTid().longValue()).getName());
        fileTable.setProjectName(projectService.getProjectInfoById(fileTable.getPid().longValue()).getProjectname());
        if (Objects.isNull(scoreService.selectByFid(fileTable.getId()))) {
            fileTable.setScore("待批改");
        } else {
            fileTable.setScore(scoreService.selectByFid(fileTable.getId()).getScore().toString());
        }
    }

    @GetMapping("/classtable")
    public String classTable() {
        return "student/classtable";
    }

    @GetMapping("/getCourseTable")
    @ResponseBody
    public JSONArray getCourseTable(HttpServletRequest request, Integer ssid) {

        request.getParameter("ssid");
        //获取student信息
        Student student = (Student) request.getSession().getAttribute("student");
        Long sid = student.getId();
        ArrayList<CourseTable> coursesInfo = courseTableService.getCourseInfoBySid(Math.toIntExact(sid));
        List<CourseTableCo> courseTableCos = coursesInfo.stream()
                .map(m -> StudentConvert.toCo(m))
                .collect(Collectors.toList());
        JSONArray jsonObject = JSONArray.fromObject(courseTableCos);
        log.info(jsonObject.toString());
        return jsonObject;
    }

}
